<template>
  <div>
    <div class="bg-color-white pad-20">
      <el-row class="hint-area" v-show="hintVisible">
        <el-col :span="18">
          <span
            class="pad-l-20">当前已【{{this.partnerDefaultExamineFlag === 1 ? '开启' : '关闭'}}】自动审核二级合伙人申请，可前往参数设置{{this.partnerDefaultExamineFlag === 1 ? '关闭' : '开启'}}。</span>
          <el-button type="text" @click="linkSetting">立即前往</el-button>
        </el-col>
        <el-col :span="6" align="right">
          <el-button type="info" icon="el-icon-close" class="hint-icon" circle @click="closeHint"></el-button>
        </el-col>
      </el-row>
      <div class="top-operate-default">
        <div class="search-item">
          <label>搜索合伙人：</label>
          <el-select v-model="textCol" placeholder="请选择" style="width: 150px">
            <el-option label="合伙人名称" value="partnerName"></el-option>
            <el-option label="联系电话" value="phone"></el-option>
            <!-- 关联的一级合伙人微店信息 -->
            <el-option label="微客昵称" value="memberNickname"></el-option>
            <el-option label="微客手机号" value="memberPhone"></el-option>
            <el-option label="一级合伙人名称" value="onePartnerName"></el-option>
            <el-option label="一级合伙人联系人名称" value="onePartnerRealName"></el-option>
            <el-option label="一级合伙人手机号" value="onePartnerPhone"></el-option>
          </el-select>
          <el-input v-model="textValue" @keyup.enter.native="handleSearch" placeholder="请输入搜索关键字" style="width: 200px">
          </el-input>
          <label class="mar-l-20">创建时间：</label>
          <el-date-picker v-model="datePicker" type="daterange" unlink-panels range-separator="至"
            value-format="yyyy-MM-dd" start-placeholder="创建开始时间" end-placeholder="创建结束时间"
            :picker-options="pickerOptions">
          </el-date-picker>
          <label class="mar-l-20">状态：</label>
          <el-select v-model="partnerStatus" placeholder="请选择状态" class="pad-l-10">
            <el-option v-for="item in partnerStatuss" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="tabs-box mar-t-15">
        <el-tabs type="card" v-model="applyStatus" @tab-click="initEntityList">
          <el-tab-pane :label="passedLabel" name="1"></el-tab-pane>
          <el-tab-pane :label="waitCheckLabel" name="0"></el-tab-pane>
          <el-tab-pane :label="rejectLabel" name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
              class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <div v-if="applyStatus == '1'">
            <el-button class="batch-btn" @click="handleCommand('0')">批量启用</el-button>
            <el-button class="batch-btn" @click="handleCommand('1')">批量禁用</el-button>
          </div>
          <div v-if="applyStatus == '0'">
            <el-button class="batch-btn" @click="handleBatchPass(undefined)">批量通过</el-button>
            <el-button class="batch-btn" @click="handleBatchReject(undefined)">批量拒绝</el-button>
          </div>

          <!-- <el-button type="mini" @click="buttonAdd" >默认提成比例</el-button> -->
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="entityList" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header"
          row-class-name="default-row">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column width="220px" label="合伙人信息" fixed="left">
            <template slot-scope="scope">
              <div>
                {{ scope.row.partnerName }}
              </div>
              <div>
                手机号: {{ scope.row.phone }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="250px" label="关联店主" v-if="applyStatus == '1'">
            <template slot-scope="scope">
              <div v-if="scope.row.memberAvatar" style="float: left">
                <img :src="scope.row.memberAvatar" width="50px">
              </div>
              <div v-if="scope.row.memberNickname" style="float: left; margin-left: 2px">
                <div>
                  昵称：{{ scope.row.memberNickname }}
                </div>
                <div>
                  手机：{{ scope.row.memberPhone }}
                </div>
              </div>
              <div v-else style="float: left; margin-left: 2px; color: #c3c4c5">—</div>
            </template>
          </el-table-column>
          <el-table-column label="上级合伙人信息" width="200px">
            <template slot-scope="scope">
              <div>
                {{ scope.row.onePartnerName }}
              </div>
              <div>
                联系人：{{ scope.row.onePartnerRealName }}
              </div>
              <div>
                手机号: {{ scope.row.onePartnerPhone }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="已激活云店数" prop="twoMemberNum" width="200px" v-if="applyStatus == '1'"></el-table-column>
          <el-table-column width="160px" label="招募主播数" v-if="applyStatus == '1'">
            <template slot-scope="scope">
              <span>{{ scope.row.oneRecruitedAnchorNum ? scope.row.oneRecruitedAnchorNum : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="创建时间" prop="createTime" v-if="applyStatus == '1'"></el-table-column>
          <el-table-column width="150px" label="状态" prop="statusFlag" v-if="applyStatus == '1'">
            <template slot-scope="scope">
              <span v-if="scope.row.partnerStatus == 0">启用</span>
              <span v-else>禁用</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="申请时间" prop="applyDate" v-if="applyStatus == '0'" key="99">
          </el-table-column>
          <el-table-column width="200px" label="拒绝时间" prop="rejectDate" v-if="applyStatus == '2'" key="100">
          </el-table-column>
          <el-table-column width="150px" label="拒绝原因" prop="rejectReason" v-if="applyStatus == '2'" key="101">
            <template slot-scope="scope">
              <el-popover placement="top" width="220" trigger="click">
                <div class="flex-col">
                  <span>{{ scope.row.rejectReason }}</span>
                </div>
                <el-button slot="reference" type="text">查看原因</el-button>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="240px" align="right" fixed="right">
            <template slot-scope="scope">
              <div v-if="applyStatus == '1'">
                <el-button type="text" size="medium" @click="updateEntity(scope.row)">设置</el-button>
                <el-button type="text" size="medium" @click="updateStatus(scope.row.partnerId, 0)"
                  v-if="scope.row.partnerStatus == 1">启用</el-button>
                <el-button type="text" size="medium" @click="updateStatus(scope.row.partnerId, 1)"
                  v-if="scope.row.partnerStatus == 0">停用</el-button>
                <el-button type="text" size="medium" @click="handleDelete(scope.row.partnerId)"
                  v-if="scope.row.partnerStatus == 1">删除</el-button>
                <el-button type="text" size="medium" @click="doResetPwd(scope.row.partnerId)">重置密码</el-button>
              </div>
              <div v-if="applyStatus == '0'">
                <el-button type="text" size="medium" @click="handleBatchPass(scope.row)">通过</el-button>
                <el-button type="text" size="medium" @click="handleBatchReject(scope.row)">拒绝</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加/编辑 -->
    <div>
      <el-dialog width="500px" v-el-drag-dialog :visible.sync="dialogFormVisible" :before-close="handleDialogClose">
        <el-form ref="recruiterForm" :model="form" :rules="rules" label-position="right" label-width="100px"
          style='width: 80%; margin-left:50px;'>
          <el-row>
            <el-form-item label-width="100px" :label="ratioName" prop="royaltyRatio">
              <el-input v-model="form.royaltyRatio" placeholder="比例限制在1~100之间">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="saveData">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 拒绝弹窗 -->
    <el-dialog title="拒绝原因" width="400px" v-el-drag-dialog :visible.sync="rejectVisible">
      <el-input type="textarea" :rows="3" v-model="rejectForm.rejectReason" placeholder="请输入拒绝原因"
        class="pad-l-30 pad-r-30"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doCancelReject">取消</el-button>
        <el-button type="primary" @click="doSaveReject">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<style scoped>

</style>

<script>
  import {
    pagingPartner,
    updateBatchStatus,
    savePartner,
    doResetPwd,
    deleteById,
    getTwoPartnerRoyaltyRatio,
    saveEnterpriseConfig,
    statTwoPartner,
    updateBatchApplyStatus
  } from '@/api/user/enterprisePartner'
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import Tinymce from '@/components/Tinymce'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  export default {
    components: {
      Tinymce
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        partnerStatuss: [{
          value: '',
          label: '全部'
        }, {
          value: '0',
          label: '启用'
        }, {
          value: '1',
          label: '禁用'
        }],
        // 搜索框下拉选项
        textCol: 'partnerName',
        // 搜索值
        textValue: '',
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          currentPage: 1,
          size: 10,
          partnerType: 2,
          startTime: '',
          endTime: ''
        },
        // 查询条件
        searchListQuery: {},
        partnerStatus: '',
        datePicker: [],
        entityList: [],
        royaltyRatioType: 1,
        royaltyRatio: 0,
        ratioName: '提成比例',
        total: null,
        listLoading: true,
        multipleSelection: [],
        partnerIds: [],
        form: {
          royaltyRatio: 0,
          enterpriseId: ''
        },
        searchKeyword: '',
        dialogFormVisible: false,
        dialogStatus: '',
        isHaveDict: false,
        recruiterCount: 0,
        memberCount: 0,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        rules: {
          royaltyRatio: [{
            required: false,
            message: '请输入提成比例',
            trigger: 'blur'
          },
          {
            pattern: /(^(\d|[1-9]\d|100)(\.\d{1,2})?$)/,
            message: '请输入正确提成比例'
          }
          ]
        },
        Map: {},
        allChecked: false,
        rejectVisible: false,
        // 拒绝表单数据
        rejectForm: {
          rejectReason: '',
          partnerId: ''
        },
        // 自动审核提示
        hintVisible: true,
        partnerDefaultExamineFlag: 0,
        // 申请状态
        applyStatus: '1',
        passedLabel: '已通过(0)',
        waitCheckLabel: '待审核(0)',
        rejectLabel: '已拒绝(0)',
        dateColumn: 'createTime'
      }
    },

    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      this.initEnterpriseConfig()
      this.initEntityList()
      this.initStatTwoPartner()
    },
    methods: {
      initEnterpriseConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          // this.hintVisible = response.data.partnerDefaultExamineFlag === 1
          this.partnerDefaultExamineFlag = response.data.partnerDefaultExamineFlag
        })
      },
      // 自动审核提示框关闭事件
      closeHint() {
        this.hintVisible = false
      },
      // 跳转系统参数事件
      linkSetting() {
        this.$router.push({
          path: '/system/system-config/index',
          query: {
            active: 'partner-set'
          }
        })
      },
      close() {
        this.dialogFormVisible = false
      },
      handleDialogClose() {
        this.dialogFormVisible = false
      },
      // 拒绝事件
      handleBatchReject(row) {
        if (row === undefined) {
          if (this.multipleSelection.length <= 0) {
            this.$message.error('请选择要操作的数据')
            return
          }
        }
        this.rejectVisible = true
        this.rejectForm.partnerId = row.partnerId
      },
      // 拒绝取消
      doCancelReject() {
        this.rejectForm.rejectReason = ''
        this.rejectForm.partnerId = ''
        this.rejectVisible = false
      },
      // 拒绝确定
      doSaveReject() {
        const partnerIds = []
        if (this.rejectForm.partnerId) {
          partnerIds.push(this.rejectForm.partnerId)
        } else {
          if (this.multipleSelection.length > 0) {
            this.multipleSelection.forEach((item) => {
              partnerIds.push(item.partnerId)
            })
          } else {
            this.$message.error('请选择要操作的数据')
            this.rejectVisible = false
            return
          }
        }
        const params = {
          applyStatus: 2,
          partnerIds: partnerIds.join(','),
          rejectReason: this.rejectForm.rejectReason
        }
        updateBatchApplyStatus(params).then(response => {
          this.doCancelReject()
          if (response.isError) return
          this.initEntityList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
      },
      // 批量通过
      handleBatchPass(row) {
        if (row === undefined) {
          if (this.multipleSelection.length <= 0) {
            this.$message.error('请选择要操作的数据')
            return
          }
        }
        this.$confirm('确认审核通过?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const partnerIds = []
          if (row) {
            partnerIds.push(row.partnerId)
          } else {
            this.multipleSelection.forEach((item) => {
              partnerIds.push(item.partnerId)
            })
          }
          const params = {
            applyStatus: 1,
            partnerIds: partnerIds.join(','),
            rejectReason: ''
          }
          updateBatchApplyStatus(params).then(response => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        })
      },
      // 统计状态
      initStatTwoPartner() {
        statTwoPartner(this.searchListQuery).then(response => {
          let passedNum = 0
          let waitCheckNum = 0
          let rejectNum = 0
          if (!response.isError) {
            const entity = response.data
            if (entity[1]) {
              passedNum = entity[1]
            }
            if (entity[0]) {
              waitCheckNum = entity[0]
            }
            if (entity[2]) {
              rejectNum = entity[2]
            }
            this.passedLabel = '已通过(' + passedNum + ')'
            this.waitCheckLabel = '待审核(' + waitCheckNum + ')'
            this.rejectLabel = '已拒绝(' + rejectNum + ')'
          }
        })
      },
      initEntityList() {
        this.setQueryCondition()
        this.initStatTwoPartner()
        this.listLoading = true
        pagingPartner(this.searchListQuery).then(response => {
          const entityList = response.data.records
          this.entityList = entityList
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 设置查询条件
      setQueryCondition() {
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.partnerStatus = this.partnerStatus
        this.searchListQuery.dateColumn = this.dateColumn
        if (this.datePicker != null && this.datePicker.length > 0) {
          this.searchListQuery.startDate = this.datePicker[0] + ' 00:00:00'
          this.searchListQuery.endDate = this.datePicker[1] + ' 23:59:59'
        } else {
          this.searchListQuery.startDate = ''
          this.searchListQuery.endDate = ''
        }
        this.searchListQuery.applyStatus = this.applyStatus
      },
      handleCommand(command) {
        if (command === '0') {
          this.updateBatchStatus(0)
        }
        if (command === '1') {
          this.updateBatchStatus(1)
        }
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initEntityList()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initEntityList()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.entityList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 查询
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initEntityList()
      },
      // 重置查询参数
      resetSearch() {
        const originData = this.$options.data()
        console.log(originData)
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.defaultQuery = originData.defaultQuery
        this.partnerStatus = originData.partnerStatus
        this.datePicker = originData.datePicker
        this.handleSearch()
      },
      updateBatchStatus(status) {
        this.partnerIds = []
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((item) => {
            this.partnerIds.push(item.partnerId)
          })
          updateBatchStatus(this.partnerIds.join(','), status).then(response => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        } else {
          this.$message.error('请选择要操作的数据')
        }
      },
      updateStatus(id, status) {
        updateBatchStatus(id, status).then(response => {
          if (response.isError) return
          this.initEntityList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
      },
      // 默认提成比例
      buttonAdd() {
        // 清除赋值
        this.resetrecruiter()
        this.dialogStatus = 'update'
        this.ratioName = '默认提成比例'
        this.royaltyRatioType = 2
        getTwoPartnerRoyaltyRatio(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.form.royaltyRatio = response.data
          this.form.enterpriseId = this.getEnterpriseId()
          this.dialogFormVisible = true
        })
      },
      // 清空信息
      resetrecruiter() {
        this.form = {
          royaltyRatio: 0,
          enterpriseId: this.getEnterpriseId()
        }
      },
      // 保存
      saveData() {
        const that = this
        this.$refs['recruiterForm'].validate((valid) => {
          if (valid) {
            if (this.royaltyRatioType === 1) {
              this.form.enterpriseId = this.getEnterpriseId()
              savePartner(this.form).then((response) => {
                if (response.isError) {
                  return
                }
                that.initEntityList()
                that.dialogFormVisible = false
                that.$message({
                  type: 'success',
                  message: '保存成功!'
                })
              })
            } else {
              saveEnterpriseConfig(this.getEnterpriseId(), this.form.royaltyRatio).then(response => {
                if (response.isError) return
                that.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '设置成功'
                })
              })
            }
          }
        })
      },
      // 编辑
      updateEntity(row) {
        this.ratioName = '提成比例'
        this.royaltyRatioType = 1
        // 清除赋值
        this.resetrecruiter()
        this.form = Object.assign({}, this.form, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        this.$nextTick(() => {
          this.$refs['recruiterForm'].clearValidate()
        })
      },
      doResetPwd(id) {
        this.$confirm('此操作将重置密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doResetPwd(id).then((response) => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      // 删除
      handleDelete(id) {
        this.$confirm('此操作将删除合伙人，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById(id).then((response) => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {})
      },
      // 重置密码
      handlePassword(id) {
        this.$confirm('此操作将重置该招募员信息，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doResetPwd(id).then(() => {
            this.$message({
              type: 'success',
              message: '重置成功!'
            })
          })
        }).catch(() => {})
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.entityList.length) {
          this.entityList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      }
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    }
  }
</script>
<style lang="less" scoped>
  .user-avatar {
    width: 59px;
    height: 59px;
    display: block;
    border-radius: 50%;
  }

  .hint-area {
    background-color: #fdf8c8;
    padding: 10px 0;
    margin-bottom: 20px;

    .hint-icon {
      padding: 1px;
      margin: 10px 10px 0 0;
    }
  }

  .el-radio-group {
    padding-left: 5%;

    .el-radio {
      padding-top: 15px;
      display: block;
    }
  }

  .line-h-12 {
    line-height: 1.4;
  }
</style>
